<template>
	<view class="page bg-fff">
		<search />
		<!-- <menus /> -->
		<rushi-collect :list="hotPlateList" :amounts="amountlList" />

		<text class="left-15 fontBold font15">全部楼盘</text>
		<view class="filterWrap" :class="{ 'filter-fixed': isFilterOpen }">
			<filter-menu ref="filterMenuRef" :menuList="menuList" :defaultValues="defaultValues"
				@change="handleFilterChange" @filterOpen="handleFilterOpen"
				@filterClose="handleFilterClose"></filter-menu>
		</view>
		<view class="productListWrap" v-if="productList.length > 0">
			<view class="productItemWrap" v-for="item in productList" :key="item.id">
				<product-item :product="item"></product-item>
			</view>
			<up-loadmore :status="loadStatus" />
		</view>
		<up-empty mode="search" marginTop="20" v-if="productList.length === 0 && loadStatus === 'nomore'"></up-empty>
		<up-gap height="40" />
		<tabbar></tabbar>
	</view>
</template>

<script setup>
import Search from './components/search.vue';
// import Menus from './components/menus.vue';
import RushiCollect from './components/rushi-collect.vue';
import { ref } from 'vue';
import { onShow, onLoad, onReachBottom } from '@dcloudio/uni-app';
import { useConfigStore, useUserInfoStore, useIndexStore } from '@/store/index';
import { findHomeAPI, loadAllProducts } from '@/common/api/houses';

const configStore = useConfigStore();
const userInfoStore = useUserInfoStore();
const indexStore = useIndexStore();

const menuList = ref([]);

// 设置默认值
const defaultValues = ref([]);

// 筛选菜单是否打开
const isFilterOpen = ref(false);

// 筛选菜单ref
const filterMenuRef = ref(null);

let loadStatus = ref('loadmore');
let next = ref('');
let loadParams = ref({
	area: '',
	street: '',
	subway: '',
	station: '',
	amount: '',
	house: '',
	size: '',
	more: '',
	city: indexStore.nowCityCode,
	keyword: '',
	tag: ''
});

// 产品列表
let productList = ref([]);

let hotPlateList = ref([]);
let amountlList = ref([]);

// 页面显示
onShow(() => {
	//延迟1秒再验证验证是否填写上周数据
	setTimeout(async () => {
		await userInfoStore.checkLastWeekVisitData();

		if(userInfoStore.showStatisticsForm) {
			uni.showModal({
				title: '提示',
				showCancel: false,
				content: '检测到您上周未提交到访数据，请及时提交',
				success: (res) => {
					if(res.confirm) {
						uni.navigateTo({
							url: `/pages/my/statistics/form/index?startDate=${userInfoStore.statisticsFormObj.start_time}&endDate=${userInfoStore.statisticsFormObj.end_time}`
						})
					}
				}
			})
		}
	}, 1500)
})

// 初始化加载数据
onLoad((options) => {
	uni.$check_and_login(init)
});

//init
async function init() {
	try {
		await userInfoStore.checkUserInfo();//验证用户信息,如果没有就获取并且更新
		const { status, detail } = await findHomeAPI();
		if (status !== 0) {
			uni.$u.toast(detail);
			return
		}
		hotPlateList.value = detail.hot;
		amountlList.value = detail.tag;

		//获取城市筛选菜单数据
		await indexStore.getCityFilterMenuParams();
		let catchFilterData = [];
		catchFilterData = [
			{
				title: '区域',
				type: 'tree',
				data: [
					{
						id: 'area',
						name: '区域',
						children: indexStore.filterAreaList
					},
					{
						id: 'metro',
						name: '地铁',
						children: indexStore.filterMetroList
					}
				]
			},
			{
				title: '价格',
				type: 'checkbox',
				data: indexStore.filterAmountList
			},
			{
				title: '户型',
				type: 'checkbox',
				data: indexStore.filterHouseList
			},
			{
				title: '面积',
				type: 'checkbox',
				data: indexStore.filterSizeList
			},
			{
				title: '更多',
				type: 'radio',
				data: indexStore.filterTagList
			}
		];
		menuList.value = catchFilterData;
		defaultValues.value = [
			{ level1: 'area', level2: '', items: [] },
			[''],
			[''],
			[''],
			'',
		];
	} catch (error) {
		console.error('获取数据失败:', error);
	}
	await getList(true);
}


// 获取数据方法
async function getList(isRefresh = false) {
	if (isRefresh) {
		loadStatus.value = 'loadmore';
		next.value = '';
	}
	if (loadStatus.value === 'loading' || loadStatus.value === 'nomore') return;

	try {
		loadStatus.value = 'loading';
		let url = (next.value ? next.value : '/product/mall/v6/query');
		const res = await loadAllProducts(url, loadParams.value);
		if (res.status !== 0) {
			uni.$u.toast(res.detail);
			return
		}
		if (isRefresh) {
			productList.value = res.detail.results;
		} else {
			productList.value.push(...res.detail.results);
		}
		next.value = res.detail.next;
		loadStatus.value = res.detail.next ? 'loadmore' : 'nomore';
	} catch (error) { }
}

// 监听页面滚动到底部
onReachBottom(() => {
	if (loadStatus.value === 'loadmore') {
		getList();
	}
});

// 处理筛选菜单打开的逻辑
const handleFilterOpen = () => {
	isFilterOpen.value = true;
}

// 处理筛选菜单关闭的逻辑
const handleFilterClose = () => {
	isFilterOpen.value = false;

}

async function handleFilterChange(data) {
	let [treeArr, priceArr, typeArr, sizeArr, moreStr] = data.allValues;

	loadParams.value = {
		...loadParams.value,
		area: treeArr.level1 === 'area' ? treeArr.level2 : '',
		street: treeArr.level1 === 'area' ? treeArr.items.join(',') : '',
		subway: treeArr.level1 === 'metro' ? treeArr.level2 : '',
		station: treeArr.level1 === 'metro' ? treeArr.items.join(',') : '',
		amount: priceArr.join('|'),
		house: typeArr.join(','),
		size: sizeArr.join('|'),
		more: moreStr,
		city: indexStore.nowCityCode,
		keyword: '',
		tag: ''
	}
	await getList(true);
}
</script>

<style lang="scss" scoped>
.page {
	border-top: 1rpx solid #FFFFFF;
	min-height: 100vh;
	position: relative;

	.productListWrap {
		.productItemWrap {
			margin: 20rpx;
		}
	}

	.filterWrap {
		position: relative;

		&.filter-fixed {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			z-index: 100;
		}
	}
}
</style>